package com.gitee.mrj.aiboot.core.sf.generators.ui.widget;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.gitee.mrj.aiboot.annotation.config.KV;
import com.gitee.mrj.aiboot.annotation.config.sf.ui.widget.SFTransferWidget;
import com.gitee.mrj.aiboot.core.sf.generators.FormDefinitionGenerator;
import com.gitee.mrj.aiboot.core.sf.generators.UIForm;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class SFTransferWidgetGenerator implements FormDefinitionGenerator {
    @Override
    public void generate(UIForm root, Field field, UIForm node) {
        SFTransferWidget widget = AnnotatedElementUtils.findMergedAnnotation(field, SFTransferWidget.class);
        generate(node, widget);
    }


    private void generate(UIForm node, SFTransferWidget widget) {
        ObjectNode ui = node.getUi();
        ui.put("widget", "transfer");
        if (ArrayUtils.isNotEmpty(widget.titles())) {
            ArrayNode array = putArray(ui, "titles");
            for (String title : widget.titles()) {
                array.add(title);
            }
        }
        if (ArrayUtils.isNotEmpty(widget.operations())) {
            ArrayNode array = putArray(ui, "operations");
            for (String op : widget.operations()) {
                array.add(op);
            }
        }
        if (ArrayUtils.isNotEmpty(widget.listStyle())) {
            ObjectNode object = putObject(ui, "listStyle");
            for (KV op : widget.listStyle()) {
                object.put(op.key(), op.value());
            }
        }
        putString(ui, "itemUnit", widget.itemUnit());
        putString(ui, "itemsUnit", widget.itemsUnit());
        ui.put("showSearch", widget.showSearch());
        putString(ui, "searchPlaceholder", widget.searchPlaceholder());
        putString(ui, "notFoundContent", widget.notFoundContent());
    }


    @Override
    public Class[] supports() {
        return new Class[]{SFTransferWidget.class};
    }
}
